package net.ibizsys.eclipse.studio.handler;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import net.ibizsys.eclipse.studio.Activator;
import net.ibizsys.eclipse.studio.console.Console;
import net.ibizsys.eclipse.studio.data.IBizApp;
import net.ibizsys.eclipse.studio.data.Project;
import net.ibizsys.eclipse.studio.data.IBizSystem;
import net.ibizsys.eclipse.studio.data.LocalDataManager;
import net.ibizsys.eclipse.studio.data.ProjectType;
import net.ibizsys.eclipse.studio.i18n.I18n;
import net.ibizsys.eclipse.studio.util.FileKit;
import net.ibizsys.eclipse.studio.vc.SystemVCManager;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

/**
 * 重置自动发布代码项目
 * <p>
 * 删除本地项目然后再从版本控制拉取最新代码
 * 
 * @author <a href='http://www.weibo.com/xjtoo' target='_blank'>Enmaai</a>
 */
public class ResetPubHandler extends AbstractHandler
{
	public ResetPubHandler()
	{
	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException
	{
		final IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);

		if (window != null)
		{
			IStructuredSelection selection = (IStructuredSelection) window.getSelectionService().getSelection();
			Object firstElement = selection.getFirstElement();
			if (firstElement instanceof IAdaptable)
			{
				IProject project = (IProject) ((IAdaptable) firstElement).getAdapter(IProject.class);

				if (project != null)
				{
					final IBizSystem system = LocalDataManager.manager().getSystem(project.getName());

					if (system == null)
					{
						MessageDialog.openError(window.getShell(), I18n.Error, I18n.SystemDataError);
						return null;
					}

					final List<Project> projects = new ArrayList<Project>();

					for (Project ibizProject : system.getProjects())
					{
						if (ibizProject.getType().value() < ProjectType.USR.value() && ibizProject.getType().value() > ProjectType.PUB.value())
						{
							projects.add(ibizProject);
						}
					}

					for (IBizApp ibizApp : system.getApps())
					{
						for (Project ibizProject : ibizApp.getProjects())
						{
							if (ibizProject.getType().value() < ProjectType.USR.value() && ibizProject.getType().value() > ProjectType.PUB.value())
							{
								projects.add(ibizProject);
							}
						}
					}

					new Thread()
					{
						@Override
						public void run()
						{
							List<Project> list = new ArrayList<Project>();

							for (Project project : projects)
							{
								File path = new File(Activator.getDefault().getRootPath() + File.separator + project.getName());

								if (!path.exists())
								{
									continue;
								}

								FileKit.delete(path);

								if (path.exists())
								{
									Console.println("无法删除项目[" + project.getName() + "]");
									continue;
								}
								list.add(project);
							}

							final List<Project> list2 = SystemVCManager.checkout(system, list);

							Activator.getDefault().getWorkbench().getDisplay().syncExec(new Runnable()
							{
								@Override
								public void run()
								{
									importProjects(window.getShell(), list2);
								}
							});
						}
					}.start();
				}
			}
		}
		return null;
	}

	/**
	 * 导入项目到工作区间
	 * 
	 * @param list
	 */
	private void importProjects(Shell shell, final List<Project> list)
	{
		try
		{
			new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress()
			{
				@Override
				public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
				{
					for (Project proj : list)
					{
						IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(proj.getName());
						if (project != null)
						{
							try
							{	
								//project.delete(true, monitor);
								project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
								//project.open(monitor);

								Console.println("[信息]成功导入项目[" + project.getName() + "].");
							} catch (CoreException e)
							{
								Console.println("[错误]导入项目[" + project.getName() + "]失败.");
							}
						} else
						{
							Console.println("[错误]无法获取项目[" + proj.getName() + "],跳过.");
						}
					}
					Console.println("[信息]导入项目结束.");
					Console.println("[信息]重置自动发布代码项目.");
				}
			});
		} catch (Exception e)
		{
			Console.println("[错误]获取项目执行线程异常,无法导入项目,导入项目终止.");
		}
	}
}